package crud

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func UpdateMain() {
	// #region basic
	// 模型定义
	type User struct {
		ID   uint `gorm:"primarykey"`
		Name string
		Age  int8
	}

	// 数据库实例
	dsn := "root:root@tcp(127.0.0.1:3306)/test-gorm"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	// #endregion basic

	if err == nil {
		var user User

		// #region update
		user = User{}
		db.First(&user)
		user.Name = "shann"
		db.Save(&user)
		// #endregion update

		// #region single-column
		user = User{ID: 10}

		db.Model(&User{}).Where("id = ?", 10).Update("age", 30)
		// UPDATE `users` SET `age`=30 WHERE id = 10

		db.Model(&user).Update("age", 30)
		// UPDATE `users` SET `age`=30 WHERE `id` = 10

		db.Model(&user).Where("name = ?", "shann").Update("age", 30)
		// UPDATE `users` SET `age`=30 WHERE name = 'shann' AND `id` = 10
		// #endregion single-column

		// #region multiple-columns
		// 模型
		db.Model(&user).Updates(User{Name: "shann", Age: 20})
		// 映射
		db.Model(&user).Updates(map[string]interface{}{"name": "shann", "age": 20})
		// #endregion multiple-columns

		// #region selected-columns
		// 选中单列
		db.Model(&user).Select("name").Updates(map[string]interface{}{"name": "shann", "age": 22})
		// UPDATE `users` SET `name`='shann' WHERE `id` = 10

		// 忽略单列
		db.Model(&user).Omit("name").Updates(map[string]interface{}{"name": "shann", "age": 22})
		// UPDATE `users` SET `age`=22 WHERE `id` = 10

		// 选中多列
		db.Model(&user).Select("Name", "Age").Updates(User{Name: "shann", Age: 22})
		// UPDATE `users` SET `name`='shann',`age`=22 WHERE `id` = 10

		// 选中全部列
		db.Model(&user).Select("*").Updates(User{ID: 10, Name: "shann", Age: 22})
		// UPDATE `users` SET `id`=10,`name`='shann',`age`=22 WHERE `id` = 10

		// 选中全部列后忽略部分列
		db.Model(&user).Select("*").Omit("ID", "Name").Updates(User{Name: "shann", Age: 22})
		// UPDATE `users` SET `age`=22 WHERE `id` = 10
		// #endregion selected-columns
	}
}
